<?php

namespace App\Http\Middleware;

use Closure;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;

class ApiAuth
{
    public function handle($request, Closure $next)
    {
        try {
            if (! $user = JWTAuth::parseToken()->authenticate()) {  //获取到用户数据，并赋值给$user
                return response()->json([
                    'code' => 1004,
                    'message' => '无此用户'

                ], 404);
            }
            return $next($request);

        } catch (TokenExpiredException $e) {

            return response()->json([
                'code' => 1003,
                'message' => 'token 过期' ,
            ]);

        }  catch (TokenInvalidException $e) {
            return response()->json([
                'code' => 1002,
                'message' => 'token 无效',
            ]);

        } catch (JWTException $e) {

            return response()->json([
                'code' => 1001,
                'message' => '缺少token' ,
            ]);
        }
    }
}
